package com.balloon.springboot.ws.websocket;

import com.balloon.core.date.DateTimeUtils;
import com.balloon.springboot.core.jackson.JacksonObjectMapper;
import com.balloon.springboot.core.rules.ResultVO;
import com.balloon.springboot.core.spring.SpringContextHolder;
import com.balloon.springboot.redis.utils.RedisUtils;
import com.balloon.springboot.system.user.entity.SystemUser;
import com.balloon.springboot.ws.channel.ChannelSupervise;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

public class NioWebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger logger = LoggerFactory.getLogger(NioWebSocketHandler.class);

    private WebSocketServerHandshaker wsh;

    private final ConcurrentMap<String, ChannelId> channelMap = new ConcurrentHashMap<>();



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("收到消息：" + msg);
        if (msg instanceof FullHttpRequest) {
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        logger.info("客户端加入连接：" + ctx.channel());
        ChannelSupervise.addChannel(ctx.channel());

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        logger.info("客户端断开连接：" + ctx.channel().id().asLongText());
        ConcurrentMap<String, ChannelId> channelSuperviseChannelMap = ChannelSupervise.getChannelMap();
        Set<String> set = channelSuperviseChannelMap.keySet();
        for(String uid : set){
            if(channelSuperviseChannelMap.get(uid).asLongText().equals(ctx.channel().id().asLongText())){
                channelSuperviseChannelMap.remove(uid);
            }
        }
        ChannelSupervise.setChannelMap(channelSuperviseChannelMap);
        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            wsh.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            logger.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        logger.info("服务端收到：" + request);

        JacksonObjectMapper mapper = new JacksonObjectMapper();
        Map map = mapper.readValue(request, Map.class);
        String token = (String)map.get("token");

        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        String userInfoStr = redisUtils.get("SYSTEM_USER_INFO:" + token);
        SystemUser systemUser = mapper.readValue(userInfoStr, SystemUser.class);
        map.put("username", systemUser.getUsername());
        String dateStr = DateTimeUtils.formatDateTime(LocalDateTime.now(), "yyyy/MM/dd HH:mm:ss");
        map.put("dateTime", dateStr);
        String wsMsg = mapper.writeValueAsString(map);
//        Channel channel = ChannelSupervise.findChannel("777");
        TextWebSocketFrame tws = new TextWebSocketFrame(wsMsg);
//        channel.writeAndFlush(tws);

        // 群发
        ChannelSupervise.send2All(tws);
//         返回【谁发的发给谁】
//        ctx.channel().writeAndFlush(tws);

    }

    /**
     * 唯一的一次http请求，用于创建websocket
     */
    private void handleHttpRequest(ChannelHandlerContext ctx,
                                   FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        String uri = req.uri();
        Map<String, String> paramMap = getUrlParams(uri);
        //如果url包含参数，需要处理
        if (uri.contains("?")) {
            String newUri = uri.substring(0, uri.indexOf("?"));
            req.setUri(newUri);
        }
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:9092/websocket", null, false);
        wsh = wsFactory.newHandshaker(req);
        channelMap.put(paramMap.get("uid"), ctx.channel().id());
        ConcurrentMap<String, ChannelId> channelSuperviseChannelMap = ChannelSupervise.getChannelMap();
        channelSuperviseChannelMap.putAll(channelMap);
        ChannelSupervise.setChannelMap(channelSuperviseChannelMap);
        logger.info("map:{}", ChannelSupervise.getChannelMap().toString());
        if (wsh == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            wsh.handshake(ctx.channel(), req);
        }
    }

    /**
     * 拒绝不合法的请求，并返回错误信息
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static Map<String, String> getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }

        }
        return map;
    }
}